package dao

/*
   @Title  文件名称: EmployeeDao.go
   @Description 描述: DAO层EmployeeDao

   @Author  作者: leijmdas@163.com  时间(2024-03-30 10:39:52)
   @Update  作者: leijmdas@163.com  时间(2024-03-30 10:39:52)

*/

import (
	"fmt"
	"gitee.com/ichub/gofactroy/common/dbcontent"
	basemodel "gitee.com/ichub/gofactroy/common/ichubbase/model"
	"gitee.com/ichub/gofactroy/common/shop/dto"
	"gitee.com/ichub/gofactroy/common/shop/model"
	"github.com/jinzhu/gorm"
	"log"
	"strings"
	"time"
)

// const PAGE_SIZE_DEFAULT = 500
// const PAGE_SIZE_MAX = 1000
type EmployeeDAO struct {
}

var InstEmployeeDAO EmployeeDAO

/*
@title     函数名称:  Insert
@description      :  新增记录
@auth      作者:      leijmdas@163.com 时间: 2024-03-30 10:39:52
@param     输入参数名: entity *model.Employee
@return    返回参数名: int32,error
*/
func (daoInst *EmployeeDAO) Insert(entity *model.Employee) (int32, error) {

	err := dbcontent.GetDB().Create(entity).Error
	if err != nil {
		log.Println(err.Error())
		return -1, err
	}

	return entity.Id, err
}

/*
@title     函数名称:  DeleteById
@description      :  根据主键Id 删除记录

@auth      作者:      leijmdas@163.com 时间: 2024-03-30 10:39:52
@param     输入参数名: Id int32
@return    返回参数名: error
*/
func (daoInst *EmployeeDAO) DeleteById(Id int32) error {
	var entity model.Employee

	err := dbcontent.GetDB().Where("id=?", Id).Delete(&entity).Error
	return err
}

/*
@title     函数名称:  Save
@description      :  保存记录

@auth      作者:      leijmdas@163.com 时间: 2024-03-30 10:39:52
@param     输入参数名: entity *model.Employee
@return    返回参数名: int32,error
*/
func (daoInst *EmployeeDAO) Save(entity *model.Employee) (int32, error) {

	err := dbcontent.GetDB().Save(entity).Error
	if err != nil {
		log.Println(err.Error())
		return -1, err
	}
	return entity.Id, err
}

/*
@title     函数名称:  Update
@description      :  修改记录

@auth      作者:      leijmdas@163.com 时间: 2024-03-30 10:39:52
@param     输入参数名: entity *model.Employee
@return    返回参数名: int32,error
*/
func (daoInst *EmployeeDAO) Update(entity *model.Employee) (int32, error) {

	err := dbcontent.GetDB().Model(&model.Employee{}).Where("id=?", entity.Id).Updates(entity).Error
	if err != nil {
		log.Println(err.Error())
		return -1, err
	}
	return entity.Id, err
}

/*
@title     函数名称:  UpdateNotNullProps
@description      :  根据主键Id修改非nil字段

@auth      作者:      leijmdas@163.com 时间: 2024-03-30 10:39:52
@param     输入参数名: Id int64,entity map[string]interface{}
@return    返回参数名: int64,error
*/
func (daoInst *EmployeeDAO) UpdateNotNullProps(Id int32, maps map[string]interface{}) (int32, error) {

	err := dbcontent.GetDB().Model(&model.Employee{}).Where("id=?", Id).Updates(maps).Error
	return Id, err
}

/*
@title     函数名称:  UpdateMap
@description      :  根据主键Id,map修改指定字段

@auth      作者:      leijmdas@163.com 时间: 2024-03-30 10:39:52
@param     输入参数名: Id int64,entity map[string]interface{}
@return    返回参数名: int64,error
*/
func (daoInst *EmployeeDAO) UpdateMap(Id int32, maps map[string]interface{}) (int32, error) {

	err := dbcontent.GetDB().Model(&model.Employee{}).Where("id=?", Id).Updates(maps).Error
	return Id, err
}

/*
@title     函数名称:  FindById
@description      :  根据主键Id 查询记录

@auth      作者:      leijmdas@163.com 时间: 2024-03-30 10:39:52
@param     输入参数名: Id int32
@return    返回参数名: entity *model.Employee, found bool, err error
*/
func (daoInst *EmployeeDAO) FindById(Id int32) (entity *model.Employee, found bool, err error) {

	entity = new(model.Employee)

	db := dbcontent.GetDB().First(entity, Id)
	found = !db.RecordNotFound()
	err = db.Error

	return entity, found, err

}

/*
@title     函数名称:  FindByIds
@description      :  根据主键Id 查询多条记录; FindByIds("1,36,39")

@auth      作者:      leijmdas@163.com 时间: 2024-03-30 10:39:52
@param     输入参数名: pks string
@return    返回参数名: *[]model.Employee,error
*/
func (daoInst *EmployeeDAO) FindByIds(pks string) (*[]model.Employee, error) {

	var entities []model.Employee
	db := dbcontent.GetDB().Raw("select * from employee where id in (" + pks + ")").Scan(&entities)

	return &entities, db.Error
}

/*
@title     函数名称:  FindByQueryParam
@description      :  查询符合条件的记录！queryParam通用条件分页

@auth      作者:      leijmdas@163.com 时间: 2024-03-30 10:39:52
@param     输入参数名: param *dto.EmployeeQueryParam
@return    返回参数名: *[]model.Employee,error
*/
func (daoInst *EmployeeDAO) FindByQueryParam(param *dto.EmployeeQueryParam) (*[]model.Employee, error) {

	var entities []model.Employee
	limit := param.PageSize
	if limit <= ichubbase.PAGE_SIZE_ZERO {

		limit = ichubbase.PAGE_SIZE_DEFAULT

	} else if limit > ichubbase.PAGE_SIZE_MAX {

		limit = ichubbase.PAGE_SIZE_MAX

	}
	param.PageSize = limit
	if param.Current <= 0 {
		param.Current = 1
	}
	start := (param.Current - 1) * limit

	dbc := dbcontent.GetDB().Model(&model.Employee{}).Offset(start).Limit(param.PageSize)
	dbc = daoInst.buildWhere(param, dbc)

	if len(param.OrderBys) > 0 {
		rs := strings.Split(param.OrderBys, ",")

		for _, value := range rs {
			orders := strings.Split(value, "|")
			dbc = dbc.Order(strings.Join(orders, " "))
		}
	}

	err := dbc.Find(&entities).Error
	return &entities, err
}

/*
@title     函数名称:  CountByQueryParam
@description      :  计算符合条件的记录总数！queryParam通用条件

@auth      作者:      leijmdas@163.com 时间: 2024-03-30 10:39:52
@param     输入参数名: param *dto.EmployeeQueryParam
@return    返回参数名: int32, error
*/
func (daoInst *EmployeeDAO) CountByQueryParam(param *dto.EmployeeQueryParam) (int32, error) {

	var count int32
	dbc := dbcontent.GetDB().Model(&model.Employee{}).Offset(0).Limit(1)
	dbc = daoInst.buildWhere(param, dbc)

	err := dbc.Count(&count).Error

	return count, err
}

func (daoInst *EmployeeDAO) formatTime(sec int64) string {
	timeLayout := "2006-01-02 15:04:05"
	datetime := time.Unix(sec, 0).Format(timeLayout)
	return datetime
}

func (daoInst *EmployeeDAO) formatDate(sec int64) string {
	timeLayout := "2006-01-02"
	datetime := time.Unix(sec, 0).Format(timeLayout)
	return datetime
}

func (daoInst *EmployeeDAO) localTimeFormat(ptime time.Time) string {
	timeLayout := "2006-01-02 15:04:05"
	return ptime.Format(timeLayout)

}

func (daoInst *EmployeeDAO) localTimeUTCFormat(ptime time.Time) string {
	timeLayout := "2006-01-02 15:04:05"
	return ptime.UTC().Format(timeLayout)

}

func (daoInst *EmployeeDAO) localDateFormat(localDateInt basemodel.LocalDateInt) string {
	timeLayout := "2006-01-02"
	datetime := localDateInt.Time.Format(timeLayout)
	return datetime
}

func (daoInst *EmployeeDAO) localDatetimeFormat(localTimeInt basemodel.LocalTimeInt) string {
	timeLayout := "2006-01-02 15:04:05"
	datetime := localTimeInt.Time.Format(timeLayout)
	return datetime
}

/*
@title     函数名称:  buildWhere
@description      :  构造通用查询条件

@auth      作者:      leijmdas@163.com 时间: 2024-03-30 10:39:52
@param     输入参数名: param * dto.EmployeeQueryParam, dbcontent *gorm.D
@return    返回参数名: *gorm.DB
*/
func (daoInst *EmployeeDAO) buildWhere(param *dto.EmployeeQueryParam, dbc *gorm.DB) *gorm.DB {

	// 区间条件 时间，数字等

	pp := param.Param
	if pp.DateRanges != nil && len(pp.DateRanges) > 0 {
		for key := range pp.DateRanges { //取map中的数组值
			dbc = dbc.Where(fmt.Sprintf("%s BETWEEN ? and ?", key),
				daoInst.formatTime(pp.DateRanges[key][0]), daoInst.formatTime(pp.DateRanges[key][1]))
		}
	}

	if pp.IntRanges != nil && len(pp.IntRanges) > 0 {
		for key := range pp.IntRanges { //取map中的数组值
			dbc = dbc.Where(fmt.Sprintf("%s BETWEEN ? and ?", key), pp.IntRanges[key][0], pp.IntRanges[key][1])
		}
	}

	if pp.StringRanges != nil && len(pp.StringRanges) > 0 {
		for key := range pp.StringRanges { //取map中的数组值
			dbc = dbc.Where(fmt.Sprintf("%s BETWEEN ? and ?", key), pp.StringRanges[key][0], pp.StringRanges[key][1])
		}
	}

	// id in (1,2,3)
	if pp.InRanges != nil && len(pp.InRanges) > 0 {
		for key := range pp.InRanges { //取map中的数组值
			dbc = dbc.Where(fmt.Sprintf("%s in (%s)", key, pp.InRanges[key]))
		}
	}
	/*if pp.DatetimeRanges != nil && len(pp.DatetimeRanges) > 0 {
		for key := range pp.DatetimeRanges { //取map中的数组值
			dbc = dbc.Where(fmt.Sprintf("%s BETWEEN ? and ?", key),
				pp.DatetimeRanges[key][0].Format("2006-01-02 15:04:05"),
				pp.DatetimeRanges[key][1].Format("2006-01-02 15:04:05"))
		}
	}*/
	// 等于条件 或者未来支持模糊查询！

	if pp.Id != 0 {
		dbc = dbc.Where("id=?", pp.Id)
	}

	if pp.DepartmentId != 0 {
		dbc = dbc.Where("department_id=?", pp.DepartmentId)
	}

	if pp.Name != "" {

		if param.FuzzyQuery {
			dbc = dbc.Where("name like ?", "%"+pp.Name+"%")
		} else {
			dbc = dbc.Where("name=?", pp.Name)
		}

	}

	if pp.Gender != "" {

		if param.FuzzyQuery {
			dbc = dbc.Where("gender like ?", "%"+pp.Gender+"%")
		} else {
			dbc = dbc.Where("gender=?", pp.Gender)
		}

	}

	if pp.IdCard != "" {

		if param.FuzzyQuery {
			dbc = dbc.Where("id_card like ?", "%"+pp.IdCard+"%")
		} else {
			dbc = dbc.Where("id_card=?", pp.IdCard)
		}

	}

	if pp.Wedlock != "" {

		if param.FuzzyQuery {
			dbc = dbc.Where("wedlock like ?", "%"+pp.Wedlock+"%")
		} else {
			dbc = dbc.Where("wedlock=?", pp.Wedlock)
		}

	}

	if pp.NationId != 0 {
		dbc = dbc.Where("nation_id=?", pp.NationId)
	}

	if pp.NativePlace != "" {

		if param.FuzzyQuery {
			dbc = dbc.Where("native_place like ?", "%"+pp.NativePlace+"%")
		} else {
			dbc = dbc.Where("native_place=?", pp.NativePlace)
		}

	}

	if pp.PoliticId != 0 {
		dbc = dbc.Where("politic_id=?", pp.PoliticId)
	}

	if pp.Email != "" {

		if param.FuzzyQuery {
			dbc = dbc.Where("email like ?", "%"+pp.Email+"%")
		} else {
			dbc = dbc.Where("email=?", pp.Email)
		}

	}

	if pp.Phone != "" {

		if param.FuzzyQuery {
			dbc = dbc.Where("phone like ?", "%"+pp.Phone+"%")
		} else {
			dbc = dbc.Where("phone=?", pp.Phone)
		}

	}

	if pp.Address != "" {

		if param.FuzzyQuery {
			dbc = dbc.Where("address like ?", "%"+pp.Address+"%")
		} else {
			dbc = dbc.Where("address=?", pp.Address)
		}

	}

	if pp.JobLevelId != 0 {
		dbc = dbc.Where("job_level_id=?", pp.JobLevelId)
	}

	if pp.PosId != 0 {
		dbc = dbc.Where("pos_id=?", pp.PosId)
	}

	if pp.EngageForm != "" {

		if param.FuzzyQuery {
			dbc = dbc.Where("engage_form like ?", "%"+pp.EngageForm+"%")
		} else {
			dbc = dbc.Where("engage_form=?", pp.EngageForm)
		}

	}

	if pp.TiptopDegree != "" {

		if param.FuzzyQuery {
			dbc = dbc.Where("tiptop_degree like ?", "%"+pp.TiptopDegree+"%")
		} else {
			dbc = dbc.Where("tiptop_degree=?", pp.TiptopDegree)
		}

	}

	if pp.Specialty != "" {

		if param.FuzzyQuery {
			dbc = dbc.Where("specialty like ?", "%"+pp.Specialty+"%")
		} else {
			dbc = dbc.Where("specialty=?", pp.Specialty)
		}

	}

	if pp.School != "" {

		if param.FuzzyQuery {
			dbc = dbc.Where("school like ?", "%"+pp.School+"%")
		} else {
			dbc = dbc.Where("school=?", pp.School)
		}

	}

	if pp.WorkState != "" {

		if param.FuzzyQuery {
			dbc = dbc.Where("work_state like ?", "%"+pp.WorkState+"%")
		} else {
			dbc = dbc.Where("work_state=?", pp.WorkState)
		}

	}

	if pp.Code != "" {

		if param.FuzzyQuery {
			dbc = dbc.Where("code like ?", "%"+pp.Code+"%")
		} else {
			dbc = dbc.Where("code=?", pp.Code)
		}

	}

	if pp.ContractTerm != 0 {
		dbc = dbc.Where("contract_term=?", pp.ContractTerm)
	}

	if pp.WorkAge != 0 {
		dbc = dbc.Where("work_age=?", pp.WorkAge)
	}

	if pp.WorkId != "" {

		if param.FuzzyQuery {
			dbc = dbc.Where("work_id like ?", "%"+pp.WorkId+"%")
		} else {
			dbc = dbc.Where("work_id=?", pp.WorkId)
		}

	}

	return dbc

}

/*
@title     函数名称:  Demo
@description      :  代码调用示例

@auth      作者:      leijmdas@163.com 时间: 2024-03-30 10:39:52
@param     输入参数名: 无
@return    返回参数名: 无
*/
func (daoInst *EmployeeDAO) Demo() {
	//var InstEmployeeDAO = dao.InstEmployeeDAO
	entity, _, _ := InstEmployeeDAO.FindById(3)
	fmt.Println(*entity)

	var qp dto.EmployeeQueryParam
	qp.Param = new(dto.EmployeeParam)
	qp.Ini()

	entities, _ := InstEmployeeDAO.FindByQueryParam(&qp)
	/*for _, v := range *entities {
		if v.Name != nil {
			fmt.Println(v.String())
		}
	}*/
	fmt.Println(len(*entities))
	fmt.Println(qp.String())

	var sentity model.Employee
	sentity.Ini(false)
	id, _ := InstEmployeeDAO.Insert(&sentity)
	fmt.Println(id)

	ret, _, _ := InstEmployeeDAO.FindById(entity.Id)
	fmt.Println(ret.String())

	entity.Id = sentity.Id
	InstEmployeeDAO.Update(entity)

	InstEmployeeDAO.DeleteById(entity.Id)

}
